package com.du.ichat.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmojiStringUtils {
    public static SpannableString getEmojiString(Context context , String text){
        String rgFace = "\\[[^\\]]+\\]";
        Pattern ptFace = Pattern.compile(rgFace, Pattern.CASE_INSENSITIVE);
        SpannableString spannableString = new SpannableString(text);
        Matcher matcher = ptFace.matcher(spannableString);
        while (matcher.find()) {
            String key = matcher.group();
            String value = key.substring(1 , key.indexOf("]"));
            if (TextUtils.isEmpty(value)) {
                continue;
            }
            // 通过上面匹配得到的字符串来生成图片资源id
            try {
                BitmapDrawable drawable = new BitmapDrawable(context.getAssets().open("emoji/" + value + ".png"));
                drawable.setBounds(0, 0, ScreenUtils.dpToPx(context, 26), ScreenUtils.dpToPx(context, 26));
                // 通过图片资源id来得到bitmap，用一个ImageSpan来包装
                ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
                // 计算该图片名字的长度，也就是要替换的字符串的长度
                int end = matcher.start() + key.length();
                // 将该图片替换字符串中规定的位置中
                spannableString.setSpan(imageSpan, matcher.start(), end,
                        Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return spannableString;
    }
}
